var timeouts;
(function($) {
$.fn.suggest = function (settings) {
	var rand=new Date().getTime();

	var config = 
		{
			cls: 'suggestive-results',
			extra_post: '',
			suggest_url: 'about:blank',
			f:null,
			z:null,
			defval:null,
			faintclass:'faint',
			container:'body',
			mwidth:0
		};
		if (settings) $.extend(config, settings);
		

	var element=$(this);
	element.attr("autocomplete","off");
	var padding_width=(parseInt(element.css('paddingLeft')) + parseInt(element.css('paddingRight'))); 
	var swidth=(element.width() + padding_width);
	var sheight=element.height();
	var padding_height=(parseInt(element.css('paddingTop')) + parseInt(element.css('paddingBottom')));
	
	var os=element.position();
	var top_offset=(os.top + sheight + padding_height); //+ padding_height
	var left_offset=(os.left-1);
	var qw=element.parents('.q-wrapper');
	$("<div>").attr("id","suggestive-results-"+rand).css({'display':'none','width':(swidth-config.mwidth)+'px','left':left_offset+'px','top':top_offset+'px'}).addClass(config.cls).addClass('blc brc').appendTo(qw);
	var sr=$("#suggestive-results-"+rand);
	
	if(element.val()=='') {
		element.val(config.defval).addClass(config.faintclass).addClass('blc brc');	
	}
	element.dblclick(function(){
		sr.slideUp(100).html("");
		element.val(config.defval).addClass(config.faintclass).addClass('blc brc');	
	});
	element.bind('keyup.suggest',function(event){
	//console.log(event.keyCode);
	// 38 = down arrow, 40 = up arrow
	var val=element.val();
	if(timeouts) {
			clearTimeout(timeouts);
		}
		if(val.length<3) {
		sr.slideUp(100).html("");
		return true;
		} else {
		element.addClass('working');
		timeouts=window.setTimeout(function(){
		
		var request=$.post(config.suggest_url,
				   {
				   	post:val,
					extra_post:config.extra_post,
					r:rand
				   },function(data){

	if(data.length<=9) {
		sr.slideUp(200).html("");
		element.addClass('blc brc');
	} else {
		sr.slideDown(100).html(data);
		qw.removeClass('blc brc');
		element.removeClass('blc brc');
	}
		element.removeClass('working');
			});
		},400); // suggestive timeout end
		
		} // end string length
	});
	
	$("#suggestive-results-"+rand+" a.sug-res").live('click.suggest',function(event){
event.preventDefault();
	sr.slideUp(200).html("");
	element.addClass('blc brc');
	qw.addClass('blc brc');
	var r=config.f;
	if( r !== null) {
		r.apply($(this),[element]);	
	}
	
	
	});
	element.focus(function(){
		if(element.val()==config.defval) {
			element.val("");	
		}
		element.removeClass(config.faintclass);
	}).blur(function(){
		if(element.val()=='') {
			element.val(config.defval).addClass(config.faintclass).addClass('blc brc');
			qw.addClass('blc brc');	
		}
	});
	return this;
   };
})(jQuery);
